﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxCallback;
using TireService.Data;
using System.Web.Security;

namespace TireService.Web.UserControls
{
    public partial class ucEditTireSetMobile : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Callback function that saves tireset
        /// </summary>
        protected void callBackUpdateTireSet_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Update tireset
                // Input values related to TireSet Data
                // 0: TireType
                // 1: RimType
                // 2: Size
                // 3: Width
                // 4: Height
                // 5: Speedindex
                // 6: Loadindex
                // 7: Tirebrand
                // 8: Brand note / model
                // 9: Lockingbolt
                // 10: Hubcaps
                // 11: Runflat tire
                // 12: Need balancing
                // 13: Extrabolts
                // 14: Rim protection
                // Input values related to TireSet Pattern
                // 15: VF
                // 16: HF
                // 17: VB
                // 18: HB
                // Input values related to TireSet container
                // 19: CargoRoomNumber
                // Input related to defining target of editing
                // 20: TireSetId
                // 21: Update tireset pattern (true/false)
                // 22: Update tireset cargoroom (true/false)
                // 23: Update tireset data (true/false)

                string[] param = e.Parameter.Split('|');

                bool updatepattern = Convert.ToBoolean(param[21]);
                bool updatecargoroom = Convert.ToBoolean(param[22]);
                bool updatedata = Convert.ToBoolean(param[23]);

                int TireSetId = Convert.ToInt32(param[20]);

                // Initiate datalayer
                TireServiceDB db = new TireServiceDB();
                
                // Get UserId
                Guid UserId = new Guid(Membership.GetUser().ProviderUserKey.ToString());
                
                TireSet tireset = new TireSet();

                // Create tiresetlog for tireset
                TireSetLogBLL tiresetBLL = new TireSetLogBLL();

                if (TireSetId == 0)
                {
                    throw new ArgumentException("Hjulsæt ikke valgt - venligst prøv igen");
                }

                if (TireSetId != 0)
                {
                    // Load tireset
                    tireset = db.GetTireSet(TireSetId);
                }

                // Check if data should be updated
                if (updatedata)
                {
                    tireset.TireTypeId = Convert.ToInt32(param[0]);
                    tireset.RimType = Convert.ToInt32(param[1]);
                    tireset.Size = Convert.ToDecimal(param[2]);
                    tireset.Width = Convert.ToDecimal(param[3]);
                    tireset.Height = Convert.ToDecimal(param[4]);
                    if (param[5] != "0") tireset.TireSpeedIndexId = Convert.ToInt32(param[5]);
                    if (param[6] != "0") tireset.TireLoadIndexId = Convert.ToInt32(param[6]);
                    if (param[7] != "0") tireset.TireBrandId = Convert.ToInt32(param[7]);
                    if (param[8] != "") tireset.TireBrandNote = Convert.ToString(param[8]);
                    tireset.LockingBolt = Convert.ToBoolean(param[9]);
                    tireset.HubCaps = Convert.ToBoolean(param[10]);
                    tireset.RunFlatTire = Convert.ToBoolean(param[11]);
                    tireset.NeedBalancing = Convert.ToBoolean(param[12]);
                    tireset.ExtraBolts = Convert.ToBoolean(param[13]);
                    tireset.RimProtection = Convert.ToBoolean(param[14]);
                    tireset.DummyTireSet = false;
                }

                // Check if cargoroom should be updated
                if (updatecargoroom)
                {
                    // Get existing container
                    int ExistingContainerId = db.GetContainerIdForCargoRoom(Convert.ToInt32(tireset.ContainerCargoRoomId));

                    // Get new cargoroomid
                    int NewContainerCargoRoomId = db.GetContainerCargoRoomIdByContainerIdAndCargoRoomNumber(ExistingContainerId, Convert.ToInt32(param[19]));

                    // Update tireset status
                    tireset.TireSetStatusId = (int)Shared.TireSetStatus.OnStock;

                    // Check if selected containercargoroom is already used
                    TireSet TireSetOccupying = db.TireSets.SingleOrDefault(p => p.ContainerCargoRoomId == NewContainerCargoRoomId);

                    int containercargoroomid = Convert.ToInt32(tireset.ContainerCargoRoomId);

                    if (TireSetOccupying == null)
                    {
                        // No tireset is occupying the cargoroom already

                        // Update tireset
                        tireset.ContainerCargoRoomId = NewContainerCargoRoomId;

                        // Create log
                        tiresetBLL.CreateTireSetLog(db, tireset, DateTime.Now, tireset.TireSetStatusId, tireset.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul flyttet til ny lagerplads", null, null, null, null, NewContainerCargoRoomId);
                    }
                    else
                    {
                        // Other tireset occupy cargoroom - move around

                        // Reset occupying tireset cargoroom
                        TireSetOccupying.ContainerCargoRoomId = null;

                        // Update tireset
                        tireset.ContainerCargoRoomId = NewContainerCargoRoomId;

                        // Create log
                        tiresetBLL.CreateTireSetLog(db, tireset, DateTime.Now, tireset.TireSetStatusId, tireset.TireSetStatusId, UserId, "Hjul flyttet til ny lagerplads", null, null, null, null, NewContainerCargoRoomId);

                        // Give occupying tireset new cargoroom
                        TireSetOccupying.ContainerCargoRoomId = containercargoroomid;

                        // Create log for occupying tireset
                        tiresetBLL.CreateTireSetLog(db, TireSetOccupying, DateTime.Now, TireSetOccupying.TireSetStatusId, TireSetOccupying.TireSetStatusId, UserId, "Hjul flyttet til ny lagerplads", null, null, null, null, TireSetOccupying.ContainerCargoRoomId);
                    }
                }

                // Check if pattern should be updated
                if (updatepattern)
                {
                    tireset.LeftFrontTirePattern = Convert.ToDecimal(param[15]);
                    tireset.RightFrontTirePattern = Convert.ToDecimal(param[16]);
                    tireset.LeftRearTirePattern = Convert.ToDecimal(param[17]);
                    tireset.RightRearTirePattern = Convert.ToDecimal(param[18]);

                    // Create tireset log
                    tiresetBLL.CreateTireSetLog(db, tireset, DateTime.Now, tireset.TireSetStatusId, tireset.TireSetStatusId, UserId, "Opdatering af dækmønster", tireset.LeftFrontTirePattern, tireset.RightFrontTirePattern, tireset.LeftRearTirePattern, tireset.RightRearTirePattern, tireset.ContainerCargoRoomId);

                }

                // Commit changes to database
                db.SubmitChanges();

                // Dispose database connection
                db.Dispose();
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException("Fejl opstod: " + ex.Message);
            }
        }

        /// <summary>
        /// Postback function that search for tireset based on registration number
        /// </summary>
        protected void callbackpanelTireSet_Callback(object source, CallbackEventArgsBase e)
        {
            try
            {
                // Instantiate datalayer
                TireServiceDB db = new TireServiceDB();

                BusinessTireSetListView tireset = db.GetTireSetOnStockByCarRegistrationNumber(e.Parameter);

                if (tireset != null)
                {
                    // Show latest tire pattern record
                    lblVF.Text = tireset.LeftFrontTirePattern.ToString();
                    lblHF.Text = tireset.RightFrontTirePattern.ToString();
                    lblVB.Text = tireset.LeftRearTirePattern.ToString();
                    lblHB.Text = tireset.RightRearTirePattern.ToString();

                    // Show current stock location
                    lblCurrentCargoRoomValue.Text = tireset.CargoRoomNumber.ToString() + "(" + tireset.ContainerNumber + ")";

                    // Show tireset data
                    rbTireType.Items.FindByValue(tireset.TireTypeId.ToString()).Selected = true;
                    if (tireset.RimType != null) rbRimType.Items.FindByValue(tireset.RimType.ToString()).Selected = true;
                    cbExtraBolts.Checked = tireset.ExtraBolts;
                    cbHubCaps.Checked = tireset.HubCaps;
                    cbLockingBolt.Checked = tireset.LockingBolt;
                    cbNeedBalancing.Checked = tireset.NeedBalancing;
                    cbRimProtection.Checked = tireset.RimProtection;
                    cbRunFlatTire.Checked = tireset.RunFlatTire;
                    txtTireBrandNote.Text = tireset.TireBrandNote;
                    if (tireset.Height != null) ddlHeight.Items.FindByValue(tireset.Height.ToString()).Selected = true;
                    if (tireset.Width != null) ddlWidth.Items.FindByValue(tireset.Width.ToString()).Selected = true;
                    if (tireset.Size != null) ddlSize.Items.FindByValue(tireset.Size.ToString()).Selected = true;
                    if (tireset.TireBrandId != null) ddlTireBrand.Items.FindByValue(tireset.TireBrandId.ToString()).Selected = true;
                    if (tireset.TireLoadIndexId != null) ddlTireLoadIndex.Items.FindByValue(tireset.TireLoadIndexId.ToString()).Selected = true;
                    if (tireset.TireSpeedIndexId != null) ddlTireSpeedIndex.Items.FindByValue(tireset.TireSpeedIndexId.ToString()).Selected = true;

                    hfTireSetId["TireSetId"] = tireset.TireSetId;
                }
                else
                {
                    hfTireSetId["TireSetId"] = 0;
                }
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }
    }
}